package diva.pap;

import static diva.lib.lang.Lang.alert;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import diva.android_library.ActivityPresenter;
import diva.android_library.rpc.Response;
import diva.pap.affiliate.AffiliateActivity;
import diva.pap.merchant.MerchantActivity;
import diva.pap.model.Application;
import diva.pap.widget.WidgetUpdateService;

public class SettingsPresenter extends ActivityPresenter {

  protected final Application application = Application.getInstance();

  public SettingsPresenter(Activity activity) {
    super(activity);
  }

  public void onCreate(Bundle state) {
    setContentView(R.layout.settings);
    loadSettings();
    registerSaveButton();
  }

  protected void saveAndLogin() {
    correctUrl();
    LoginRequest login =
        new LoginRequest(activity, getUrl(), getUsername(), getPassword(),
            new Response<LoginRequest>() {
              public void onReuestDone(LoginRequest data) {
                if (data.isSuccess())
                  onLoginSuccess(data.isMerchant());
                else alert(getString(R.string.login_msg_loginfailed));
              }

              public void onReuestFailed() {}
            });
    login.setRequestFailedMessage(R.string.login_msg_requestfailed);
    login.send();
  }

  private void correctUrl() {
    if (!getUrl().startsWith("http")) getUrlField().setText("http://" + getUrl());
  }

  private String getPassword() {
    return getEditText(R.id.settings_password_field).getText().toString();
  }

  private String getUrl() {
    return getUrlField().getText().toString();
  }

  private EditText getUrlField() {
    return getEditText(R.id.settings_url_field);
  }

  private String getUsername() {
    return getEditText(R.id.settings_username_field).getText().toString();
  }

  private void loadSettings() {
    getUrlField().setText(application.getSettings().getServerUrl());
    getEditText(R.id.settings_username_field).setText(application.getSettings().getUsername());
    getEditText(R.id.settings_password_field).setText(application.getSettings().getPassword());
  }

  private void onLoginSuccess(boolean ismerchant) {
    application.getSettings().save(getUrl(), getUsername(), getPassword());
    alert(getString(R.string.login_msg_loginsuccess));
    if (ismerchant)
      switchActivity(new Intent(activity, MerchantActivity.class));
    else switchActivity(new Intent(activity, AffiliateActivity.class));
    startService(new Intent(activity, WidgetUpdateService.class));
  }

  private void registerSaveButton() {
    getButton(R.id.settings_button_save).setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        saveAndLogin();
      }
    });
  }
}
